package com.moorror.codegenvel.view.window.codegenxrender.view;

import com.intellij.openapi.project.Project;
import com.intellij.ui.components.JBScrollPane;
import com.moorror.codegenvel.db.mysql.utils.JdbcUtils;
import com.moorror.codegenvel.db.sqlite.entity.CodeGenXRenderConnect;
import com.moorror.codegenvel.utils.MStringUtils;
import org.apache.commons.lang3.tuple.Pair;

import javax.swing.*;
import java.awt.*;

/**
 * @Author jiyanghuang
 * @Date 2025/10/24 01:00
 */
public class AddDatabaseConnection extends JPanel{
    private JTextField tfUrl;
    private JTextField tfUsername;
    private JButton btnTest;
    private JPasswordField tfPassword;
    private JLabel labelTestStatus;
    private JPanel rootPanel;
    private JTextField tfConnectionName;

    private Project project;

    public AddDatabaseConnection(Project project){
        this.project = project;
        setLayout(new BorderLayout());
        add(new JBScrollPane(rootPanel), BorderLayout.CENTER);

        initEvent();
    }

    private void initEvent() {
        btnTest.addActionListener(event -> {
            labelTestStatus.setText("");
            if(!MStringUtils.checkStr(tfConnectionName::getText, "connect name not empty", labelTestStatus::setText)){
                return;
            }
            if(!MStringUtils.checkStr(tfUrl::getText, "url not empty", labelTestStatus::setText)){
                return;
            }
            if(!MStringUtils.checkStr(tfUsername::getText, "username not empty", labelTestStatus::setText)){
                return;
            }
            if(!MStringUtils.checkStr(tfPassword::getText, "password not empty", labelTestStatus::setText)){
                return;
            }
            Pair<Boolean, String> connectionTest = JdbcUtils.connectionTest(tfUrl.getText(), tfUsername.getText(), tfPassword.getText());
            labelTestStatus.setText(connectionTest.getRight());
        });
    }

    public void fetchValue(CodeGenXRenderConnect entity){
        entity.setName(tfConnectionName.getText());
        entity.setUrl(tfUrl.getText());
        entity.setUsername(tfUsername.getText());
        entity.setPassword(tfPassword.getText());
    }

}
